﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AFT.Parking.Entity;

namespace AFT.Parking.WebSite.Filter
{
    public class AdminOnlyAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public AdminOnlyAttribute()
        {

        }
        public AdminOnlyAttribute(bool adminOnly)
        {
            _adminOnly = adminOnly;
        }


        private bool _adminOnly = true;
        /// <summary>
        /// 重写Action执行前的操作，进行登录验证以及必要的权限验证
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (_adminOnly)
            {
                //登录信息检测，没有登录则转向管理后台登录页面
                var user = filterContext.HttpContext.Session["Customer"] as Customer;
                if (user == null)
                {
                    //没有登录，转向到登录页面
                    string redirectUrl = string.Format(
                            "/Account/Login?backUrl={0}",
                            filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.AbsolutePath)
                        );
                    filterContext.Result = new RedirectResult(redirectUrl);
                    return;
                }
            }
            base.OnActionExecuting(filterContext);
        }
    }
}